﻿#include "FileEncodeManager.h"


FileEncodeManager::FileEncodeManager()
{
    finishEncode = false;
}

void FileEncodeManager::saveEncodeData(const char *path,const unsigned int size,const QString filePath, MD5 *md5)
{
    unsigned int pathLen = strlen(path) - 7;
    if (finishEncode == false)
    {
        fstream oFile(path, ios::ate|ios::out);
        oFile << typeConver::QStringToChararry(filePath) + pathLen << "," << md5->toString() << "," << size << endl;
        oFile.close();
        finishEncode = 1;
    }
    else
    {
        fstream oFile(path, ios::out|ios::app);
        oFile << typeConver::QStringToChararry(filePath)+ pathLen << "," << md5->toString() << "," << size << endl;
        oFile.close();
    }
}

void FileEncodeManager::createMd5(const QString filePath,const unsigned int size)
{
    QString md5filePath;
    MD5 md5;
    md5.reset();
    ifstream checkFile(typeConver::QStringToChararry(filePath), ios::in | ios::binary);
    md5.update(checkFile);
    checkFile.close();
    md5filePath = m_fileRootPath + "/MD5.csv";
    saveEncodeData(typeConver::QStringToChararry(md5filePath), size, filePath, &md5);
}

bool FileEncodeManager::setFileEncodePath(const QString fileEncodePath)
{
    QFileInfo fileInfo(fileEncodePath);
    if(fileInfo.isDir())
    {
        m_fileRootPath = fileEncodePath;
        if(FileFunction::getAllFileInfoList(fileEncodePath,&m_fileInfoList))
            return true;
        else
            return false;
    }
    else if(fileInfo.isFile())
    {
        m_fileRootPath = fileInfo.absolutePath();
        m_fileInfoList.append(fileInfo);
        return true;
    }
    return false;
}

void FileEncodeManager::on_fileEncode()
{
    QList<QFileInfo>::iterator item;
    for(item = m_fileInfoList.begin(); item != m_fileInfoList.end(); item++)
    {
        createMd5(item->absoluteFilePath(), item->size());
    }
    m_fileInfoList.clear();
    finishEncode = false;
}
